# -*- coding: UTF-8 -*-
# 配置默认是否触发诊断
# 作用: 给对应错误码的json文件添加 isDiagnosis 字段, 以用于判断是否会触发诊断
# 副作用: 会给json配置内的字段按key值首字母序重排序 -_-||

import os
import json
import traceback

# 这个python文件所在路径
FOLDER_PATH = os.path.dirname(__file__)  # 替换为你的文件夹路径

# python错误码文件夹所在目录，目前应该在这个文件的上一层
ECODE_FOLDER_BASE_PATH = os.path.join(FOLDER_PATH, "..")

ECODE_PATH_LIST = ["CONTROLLER", "RIO_OR_EXTIO", "SCB_OR_TOR_SENSOR", "SERVO"]

# 诊断状态位 key
DIAGNOSIS_KEY = "isDiagnosis"

NO_DIAGNOSIS = 0  # 不触发诊断
YES_DIAGNOSIS = 1  # 触发诊断


def for_each_folder(folder_list, callback):
    for folder in folder_list:
        full_path = os.path.join(ECODE_FOLDER_BASE_PATH, folder)
        if os.path.exists(full_path):
            callback(full_path)
        else:
            print("Error! path {} does not exist.".format(full_path))


def folder_callback(folder):
    files = os.listdir(folder)
    for_each_file(files, file_callback, folder)


def for_each_file(file_list, callback, folder):
    for filename in file_list:
        callback(filename, folder)


def file_callback(filename, folder):
    """
    根据文件名称设置是否诊断状态位
    """

    strip_file_name = filename.strip()
    fullpath = os.path.join(folder, filename)
    if not strip_file_name.endswith(".json"):
        print("Info! Skip {}".format(fullpath))
        return

    try:
        errcode = int(strip_file_name[:-5], 16)
    except ValueError:
        print("Error! failed to parse {}".format(filename))
        return

    if not os.path.exists(fullpath):
        print("Error! file {} no found.".format(fullpath))

    # print('load json {}'.format(fullpath))
    fp = open(fullpath, "r")
    json_data = json.load(fp)

    json_data[DIAGNOSIS_KEY] = get_trigger_diagnosis_flag(errcode)

    fp = open(fullpath, "w")
    json.dump(json_data, fp, ensure_ascii=False, sort_keys=True, indent=4)


def get_trigger_diagnosis_flag(ecode):
    # 默认参照既往版本1.7.1_28_alpha
    if ((ecode >> 16) & 0xF0) == 0x10:
        return YES_DIAGNOSIS

    if ecode & 0xFFFFFFF == 0xF0034:
        return YES_DIAGNOSIS

    if ecode & 0xFFFFF == 0xF0061:
        return NO_DIAGNOSIS

    if ecode & 0xFFFF == 0x0061:
        return YES_DIAGNOSIS

    if ecode == 0x0FFFFE:
        return YES_DIAGNOSIS

    if ecode == 0x0FFFFF:
        return YES_DIAGNOSIS

    return NO_DIAGNOSIS


def main():
    print("== start ==")
    for_each_folder(ECODE_PATH_LIST, folder_callback)
    print("== finish ==")


if __name__ == "__main__":
    main()
